package com.hobby4fun.flex.utils
{
	import mx.charts.chartClasses.StackedSeries;
	import mx.controls.Alert;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	
	public class HttpServiceUtil
	{
		/**
		 * Get XML content from URL
		 * 
		 * @param urlStr : String eg 'data/myFile.xml' or 'http://someServer/rootContext/etc/myFile.xml'
		 * @param resultHandler : Function to handle response in e4x format
		 * @param resultFormat : String eg "e4x"
		 * @param faultHandler : Function to handle error
		 * @param requestTimeoutSec : request timeout in seconds (default is 10 seconds)
		 * @param params : Object eg { abc: "123", def: "456" };
		 * @return HttpService
		 */		
		public static function xmlFileReaderService(urlStr:String,
			resultHandler:Function=null, resultFormat:String=null, faultHandler:Function=null,  
			requestTimeoutSec:int=10, params:Object=null) : HTTPService
		{
			var service:HTTPService = new HTTPService();
			service.url = urlStr;
			service.showBusyCursor = true;
			service.method = "GET";
			if (resultFormat != null) {
				service.resultFormat = resultFormat;
			}
			service.useProxy = false;
			service.requestTimeout = requestTimeoutSec;
			
			if (resultHandler == null) {
				service.addEventListener(ResultEvent.RESULT, defaultResultHandler);
			} else {
				service.addEventListener(ResultEvent.RESULT, resultHandler);
			}
			
			if (faultHandler == null)
			{
				service.addEventListener(FaultEvent.FAULT, defaultFaultHandler);
			} else {
				service.addEventListener(FaultEvent.FAULT, faultHandler);
			}
			
			return service;
		}
		
		private static function defaultResultHandler(event:ResultEvent) : void
		{
			var xmlData:XML = event.result as XML;
			Alert.show(xmlData);
			var xmlDataAsString:String = xmlData.toXMLString();
		}

		private static function defaultFaultHandler(event:FaultEvent) : void
		{
			Alert.show(event.fault.faultString, event.fault.faultCode);
		}
		
	}
}